//
//  UploadViewController.m
//  iFlickr
//
//  Created by 张 霄鹤 on 09-5-17.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "UploadViewController.h"

#import "ViewControllerChooser.h"

#import "ItemEditViewController.h"

#import "SendViewController.h"

#import "UploadItem.h"

#import "DataManager.h"

#import "ProgressViewController.h"

#import "UIImage+Extras.h"


@implementation UploadViewController

@synthesize table;

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if (self = [super initWithStyle:style]) {
    }
    return self;
}
*/


- (void)viewDidLoad {
    [super viewDidLoad];

	// 判断是否支持照相机，不支持的，那么将 btnCamera屏蔽
	
	if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
		// TODO 支持情况
		btnCamera.enabled = YES;
	}else{
		// TODO 不支持情况
		btnCamera.enabled = NO;
	}
	
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
	self.navigationItem.title = [NSString stringWithString:(NSLocalizedStringFromTable(@"UPLOAD_PHOTOS",@"main",@""))];
	picTitle = [NSString stringWithString:(NSLocalizedStringFromTable(@"IMAGE",@"main",@""))];
	if(imgs == nil){
		imgs = [[NSMutableArray alloc] init];
		picNumber = 1;
	}
}
/*
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}
*/
/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
	[super viewDidDisappear:animated];
}
*/

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
	if(imgs != nil){
		[imgs removeAllObjects];
	}
}

-(void)reloadImages{
	[self.table reloadData];
}


#pragma mark -
#pragma mark UINavigationControllerDelegate

-(void)navigationController:(UINavigationController *)navigationController
	  didShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
	// TODO 不需要
}

-(void)navigationController:(UINavigationController *)navigationController
	 willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
	// TODO 不需要
}



// UIImagePickerControllerDelegate 实现

// 对于3.0实现，需要使用另外的 方法

#ifndef __IPHONE_3_0
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
	UploadItem *uitem = [[UploadItem alloc] init];
	uitem.image = image;
	// 每次添加都变化
	uitem.title = [NSString stringWithFormat:@"%@ %d",picTitle,picNumber];
	// 采取加1操作
	picNumber++;
	[imgs addObject:uitem];
	
	[picker dismissModalViewControllerAnimated:NO];
	
	// TODO 刷新数据表格
	[self.table reloadData];
	// TODO 检查是否释放成功
	[uitem release];
}
#else
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
	UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
	UploadItem *uitem = [[UploadItem alloc] init];
	uitem.image = image;
	// 每次添加都变化
	uitem.title = [NSString stringWithFormat:@"%@ %d",picTitle,picNumber];
	// 采取加1操作
	picNumber++;
	[imgs addObject:uitem];
	
	
	[picker dismissModalViewControllerAnimated:NO];
	
	// TODO 刷新数据表格
	[self.table reloadData];
	
	[uitem release];
}
#endif

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
	[picker dismissModalViewControllerAnimated:NO];
}


-(IBAction)takePhoto:(id)sender{
	// TODO 从图片库获取
	if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
		if(pickerController == nil){
			pickerController = [[UIImagePickerController alloc] init];      // TODO 检查这个的释放情况
		}
		pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
		pickerController.delegate = self;
				
		[self.navigationController presentModalViewController:pickerController animated:NO];
	}
}

-(IBAction)takeCamera:(id)sender{
	// TODO 从照相机获取
	if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
		if(pickerController == nil){
			pickerController = [[UIImagePickerController alloc] init];
		}
		pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
		pickerController.delegate = self;
		
		
		[self.navigationController presentModalViewController:pickerController animated:NO];
	}else{
		// TODO 增加针对不支持照相的设备的支持
	}
}

#pragma mark -
#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
	if(buttonIndex == 0){
		// TODO Index 0
	}else if(buttonIndex == 1){
		// TODO Index 1 经过测试，当对话框有两个按钮，一个是 Cancel 另一个是别的的时候 证明 Cancel == 0 其余的累加
		UIViewController *authView = [[ViewControllerChooser sharedChooser] choose:VCC_ID_AUTH];
		[self.navigationController pushViewController:authView animated:YES];
	}
}

/**
 * 检查当前是否有需要上传的图像
 */
-(BOOL)haveNeedUpload{
	BOOL bret = NO;
	if(imgs){
		int con = [imgs count];
		if(con > 0){
			UploadItem *uitem;
			int state;
			for (int i = 0; i<con; i++) {
				uitem = (UploadItem *)[imgs objectAtIndex:i];
				state = uitem.uploadState;
				// 如果状态是错误，或者适 需要上传，则上传
				if(state != US_UPLOADED){
					bret = YES;
					break;
				}
			}
		}
	}
	return bret;
}

/**
 * 提交数据，十分重要
 */
-(IBAction)sendPhotos:(id)sender{
	if(!isUploading){
		
		// TODO 检查用户是否已经通过授权了
		
		DataManager *dm = [DataManager sharedDataManager];
		if(![dm isAuthorized]){
			// TODO 提示用户，需要进行授权
			NSString *alTitle = [NSString stringWithString:(NSLocalizedStringFromTable(@"ERROR",@"main",@""))];
			NSString *alMessage = [NSString stringWithString:(NSLocalizedStringFromTable(@"NEED_AUTH",@"main",@""))];
			NSString *authTitle = [NSString stringWithString:(NSLocalizedStringFromTable(@"AUTH",@"main",@""))];
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alTitle message:alMessage delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:authTitle,nil];
			[alert show];
			[alert release];
		}else{
		
			// TODO 需要实现数据提交, 暂时实现直接上传，不进行界面显示
			if(imgs != nil){
				if([self haveNeedUpload]){			
					// TODO 此处的设置，必须在线程启动之前，避免多嫌程造成混乱
					//      同时，此变量还用于线程退出操作
					isUploading = YES;
					// TODO 设置进度界面
					progress = (ProgressViewController *)[[ViewControllerChooser sharedChooser] choose:VCC_ID_PROGRESS];
					progress.uploadController = self;
					// TODO 注意此处的 animated 参数，因为如果很快的进行 push pop 会造成混乱的
					[self.navigationController pushViewController:progress animated:NO];
#ifdef debug
					NSLog(@"%@",self.navigationController.viewControllers);
#endif
					// [NSThread detachNewThreadSelector:@selector(uploadImpl:) toTarget:self withObject:nil];
					if(uploadThread){
						[uploadThread release];
					}
					uploadThread = [[NSThread alloc] initWithTarget:self selector:@selector(uploadImpl:) object:nil];
					[uploadThread start];
				}else{
					// TODO 提示用户，没有需要上传的内容
					NSString *alTitle = [NSString stringWithString:(NSLocalizedStringFromTable(@"CONFIRM",@"main",@""))];
					NSString *alMessage = [NSString stringWithString:(NSLocalizedStringFromTable(@"NO_NEED_UPLOAD",@"main",@""))];
					UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alTitle message:alMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
					[alert show];
					[alert release];
				}
			}
		}
	}
}

-(void)notifyStatus:(id)arg{
	if(arg != nil){
		[progress setProgressTitle:((NSString *)arg)];
	}
}

/**
 * 图像上传，实际的方法
 */
-(void)uploadImpl:(id)notification{
	
	NSInteger con = [imgs count];
	UploadItem *img;
	DataManager *dm = [DataManager sharedDataManager];
	// TODO 此处的默认值是必须的，因为在有些情况下，不会进入到循环内部，直接跳出了
	BOOL bOK = NO;
	id ret = nil;
	for(int i = 0;i<con;i++){
		if(!isUploading){
			return;
		}
		img = (UploadItem *)[imgs objectAtIndex:i];
		if(img.uploadState != US_UPLOADED){
			img.uploadState = US_UPLOADING;
			ret = nil;
			// TODO 此处调用主线程  此处十分重要
			[self performSelectorOnMainThread:@selector(notifyStatus:) withObject:img.title waitUntilDone:YES];
			ret = [dm uploadImageToServer:[img getImageData] withParams:[img getItemInfo]];       // TODO 此处占用内存
			if([ret isKindOfClass:[NSString class]]){
				img.uploadState = US_UPLOADED;
				img.photoid = [ret copy];
				bOK = YES;
			}else{
				img.uploadState = US_ERROR;
				bOK = NO;
				// 如果出现错误，那么就不要继续循环了，直接提示出错
				break;
			}
			if(!isUploading){
				return;
			}
		}	
		// 因为使用了上传界面，这个部分就不需要了
		//if(i % 2 == 0){
		//	[self.table reloadData];
		//}
	}
	
	isUploading = NO;
	NSString *arg = nil;
	if(bOK){
		arg = @"OK";
	}else {
		arg = @"ERROR";
	}

	
	[self performSelectorOnMainThread:@selector(doFinish:) withObject:arg waitUntilDone:NO];
}

/**
 * 上传完毕或者任务取消的情况下，执行这个方法
 */
-(void)doFinish:(id)arg{
	[self.table reloadData];
	if([arg isEqualToString:@"OK"]){
		// TODO 如果当前有进度条界面 ProgressViewController 那么就 Pop
		[self.navigationController popViewControllerAnimated:YES];
		// 因为现在加上了上传进度界面，那么不论是上传成功，还是上传失败，都应该进行 Pop 界面的处理 by xhzhang[2009/07/17]
	} else if ([arg isEqualToString:@"ERROR"]){
		
		// TODO 如果当前有进度条界面 ProgressViewController 那么就 Pop
		[self.navigationController popViewControllerAnimated:NO];   // 出错的时候，为了让 对话框快速的显示出来，所以设置程 NO
		// 因为现在加上了上传进度界面，那么不论是上传成功，还是上传失败，都应该进行 Pop 界面的处理 by xhzhang[2009/07/17]
		
		NSString *alTitle = [NSString stringWithString:(NSLocalizedStringFromTable(@"ERROR",@"main",@""))];
		NSString *alMessage = [NSString stringWithString:(NSLocalizedStringFromTable(@"UPLOAD_ERROR",@"main",@""))];
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:alTitle message:alMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
		[alert show];
		[alert release];
	} else if ([arg isEqualToString:@"CANCEL"]){
		// TODO 如果当前有进度条界面 ProgressViewController 那么就 Pop
		[self.navigationController popViewControllerAnimated:NO];   // 出错的时候，为了让 对话框快速的显示出来，所以设置程 NO
		// 因为现在加上了上传进度界面，那么不论是上传成功，还是上传失败，都应该进行 Pop 界面的处理 by xhzhang[2009/07/17]
	}
}

-(void)stopUpload{
	if(uploadThread){
		if([uploadThread isExecuting]){
			[uploadThread cancel];
			isUploading = NO;
		}
	}
	[self performSelectorOnMainThread:@selector(doFinish:) withObject:@"CANCEL" waitUntilDone:YES];
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	NSInteger ret = 0;
	if(section == 0){
		if(imgs != nil){
			//if([imgs count] > 0){
				ret = [imgs count];
			//}
		}
	}
    return ret;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
#ifndef __IPHONE_3_0
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
#else
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
#endif
    }
    
    // Set up the cell...
	NSString *ctitle = nil;
	
	// TODO 设置 cell 的 a
	cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
	
	NSInteger section = indexPath.section;
	NSInteger row = indexPath.row;
	if(section == 0){
		if(imgs != nil){
			id d = [imgs objectAtIndex:row];
			if([d isKindOfClass:[UploadItem class]]){
				UploadItem *uitem = d;
				ctitle = uitem.title;
				if(uitem.uploadState == US_UPLOADED){
					cell.accessoryType = UITableViewCellAccessoryCheckmark;
				}
				// TODO 设置图像
				
				CGFloat ch = cell.frame.size.height;
					
				
				
				UIImage *uimage = uitem.image;
				
#ifndef __IPHONE_3_0
				cell.image = [uimage imageByScalingProportionallyToSize:CGSizeMake(ch,ch)];				
#else
				CGFloat iw = uitem.image.size.width;
				CGFloat ih = uitem.image.size.height;
				CGFloat sx = ch / iw;
				CGFloat sy = ch / ih;
				cell.imageView.image = uimage;
				// 使用这种方法可以将图像缩小，但是比例需要检查
				cell.imageView.transform = CGAffineTransformMakeScale(sx, sy);
#endif
				
				
			}
		}
	}
#ifndef __IPHONE_3_0
	cell.text = ctitle;
#else
    cell.textLabel.text = ctitle;
#endif
	
	
	
    return cell;
}

/**
 * 根据图像上传列表，指定选种的位置，来进行编辑或者共享
 */
-(void)doImageWork:(NSIndexPath *)indexPath{
	UploadItem *uitem = [imgs objectAtIndex:indexPath.row];
	// TODO 此处针对iFlick版本，暂时不提交到 App Store
	/*
	if(uitem.uploadState == US_UPLOADED){
		// TODO 上传成功的就要进入共享部分
		SendViewController *sendViewController = (SendViewController *)[[ViewControllerChooser sharedChooser] choose:VCC_ID_SHARE];
		sendViewController.shareItem = uitem;
		[self.navigationController pushViewController:sendViewController animated:YES];
	}else{
	*/
		ItemEditViewController *editViewController = (ItemEditViewController *)[[ViewControllerChooser sharedChooser] choose:VCC_ID_EDIT];
		editViewController.editItem = uitem;
		editViewController.uvc = self;
		// TODO 调试这个地方是否正常
		[editViewController.tableView reloadData];
		[self.navigationController pushViewController:editViewController animated:YES];
	/*
	}
	 */
}

/**
 * 当表格单元中的标记 accessory部分被点击时，执行相应操作
 */
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath{
	[self doImageWork:indexPath];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
	// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:@"AnotherView" bundle:nil];
	// [self.navigationController pushViewController:anotherViewController];
	// [anotherViewController release];
	//UIViewController *about = [[ViewControllerChooser sharedChooser] choose:VCC_ID_ABOUT];
//	[self.navigationController pushViewController:about animated:YES];
	
	[self doImageWork:indexPath];
	
	// 此处进行选种取消操作
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
}



// Override to support conditional editing of the table view.
/**
 * 检查哪些可以编辑
 */
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
	NSInteger section = indexPath.section;
	BOOL ret = NO;
	if(section == 0){
		ret = YES;
	}
    return ret;
}



// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        //[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
		NSInteger row = indexPath.row;
		if(imgs != nil){
			NSInteger cc = [imgs count];
			if(row < cc){
				// TODO 表格的删除要确保数据更新
				[imgs removeObjectAtIndex:row];     // TODO 下面语句每次都创建新的 NSArray
				[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
			}
		}
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

- (void)dealloc {
	if(pickerController){
		[pickerController release];
	}
	if(imgs){
		[imgs release];
	}
	if(uploadThread){
		if([uploadThread isExecuting]){
			[uploadThread cancel];
		}
		if([uploadThread isCancelled]){
			[uploadThread release];
		}
	}
    [super dealloc];
}


@end

